let express = require("express");
let router = express.Router();
let multiparty = require("multiparty");
let xlsx = require("node-xlsx");
let ExcelJS = require("exceljs");
let {
  typeModel, // 类型
  deparmentModel, // 部门
  conferenceModel, // 会议
  typeClassModel, //会议教室
} = require("../model/meetingModel");

// 会议模块  查询
router.post("/list", async (req, res) => {
  const { page = 1, limit = 5, _id } = req.body;
  console.log(_id);
  let data = [];
  let skip = (page - 1) * limit;
  let total = 0;
  delete req.body.page && delete req.body.limit;
  if (Object.keys(req.body).length > 0) {
    let handle_data = req.body;
    let willgo = {};
    // 字符类参数处理
    if (handle_data.conference_name) {
      willgo.conference_name = new RegExp(handle_data.conference_name, "i");
    }
    if (handle_data.conference_theme) {
      willgo.conference_theme = new RegExp(handle_data.conference_theme, "i");
    }
    if (handle_data.apply_name) {
      willgo.apply_name = new RegExp(handle_data.apply_name, "i");
    }

    //特殊类参数处理
    if (handle_data.use_type) {
      willgo.use_type = handle_data.use_type;
    }
    if (handle_data.apply_status) {
      willgo.apply_status = handle_data.apply_status;
    }
    if (handle_data.check_status) {
      willgo.check_status = handle_data.check_status;
    }

    // 时间类参数处理
    if (handle_data.use_start_time) {
      const start = new Date(handle_data.use_start_time);
      willgo.$and = [{ use_start_time: { $gt: start } }];
    }
    if (handle_data.use_end_time) {
      if (willgo.$and) {
        const end = new Date(handle_data.use_end_time);
        willgo.$and.push({ use_end_time: { $lt: end } });
      } else {
        const end = new Date(handle_data.use_end_time);
        willgo.$and = [{ use_end_time: { $lt: end } }];
      }
    }

    data = await conferenceModel
      .find(willgo)
      .populate("use_type")
      .populate("apply_department")
      .skip(skip)
      .limit(limit);
    data_length = await conferenceModel
      .find(willgo)
      .populate("use_type")
      .populate("apply_department");
    total = data_length.length;
  } else {
    data = await conferenceModel
      .find()
      .populate("use_type")
      .populate("apply_department")
      .skip(skip)
      .limit(limit);
    data_length = await conferenceModel
      .find()
      .populate("use_type")
      .populate("apply_department");
    total = data_length.length;
  }

  res.send({
    code: 200,
    message: "获取列表成功",
    data,
    total
  });
});
// 会议预约教室
router.post("/booklist", async (req, res) => {
  let room = req.body.classrooms;
  console.log(req.body, "教室预约");
  let page = req.query.page || 1;
  let limit = req.query.limit || 90;
  let skip = (page - 1) * limit;
  if (room) {
    let data = await conferenceModel
      .find({
        $and: [{ conference_theme: room }, { apply_status: 1 }],
      })
      .populate("apply_department")
      .lean();
    for (let i = 0; i < data.length; i++) {
      let start = new Date(data[i].use_start_time);
      let endstart = new Date(data[i].use_end_time);

      let startTimes = getConferenceList(start);
      console.log(startTimes, "新的时间");

      let endTimes = getConferenceList(endstart);
      // console.log(startTimes, endTime, "时间s");
      data[i].use_start_time = startTimes;
      data[i].use_end_time = endTimes;
    }

    var Daysa = [];
    for (let i = 0; i < data.length; i++) {
      let start = new Date(data[i].use_start_time);
      let endstart = new Date(data[i].use_end_time);

      let startTimes = getConferenceList(start);
      console.log(startTimes, "新的开始时间");

      let endTimes = getConferenceList(endstart);
      console.log(endTimes, "新的结束时间");
      data[i].use_start_time = startTimes;
      data[i].use_end_time = endTimes;
      // 遍历时间
      let timeArray = [];
      let current = new Date(start);
      console.log(current, "current");
      // 过程
      while (current <= endstart) {
        timeArray.push(current);
        current = new Date(current.getTime() + 60 * 1000); // 增加一分钟
      }
      timeArray.forEach((time) => {
        let formattedTime = `${time.getFullYear()}/${time.getMonth() + 1
          }/${time.getDate()} ${time.getHours()}:${time.getMinutes()}`;
        console.log(formattedTime);
        let startDays = formattedTime.split(" ")[0].split("/")[2]; //开始号
        let startHours = formattedTime.split(" ")[1].split(":")[0]; //开始小时
        let startMints = formattedTime.split(":")[1]; //开始分钟

        //开始
        let addDays = {
          days: startDays,
          hours: startHours,
          minutes: startMints,
        };
        addDayToDaysa(addDays, Daysa);
      });
      console.log(Daysa, "数据时间结构"); // 输出添加后的完整数据结构
    }
    res.send({
      code: 200,
      message: "获取列表成功",
      data,
      Daysa,
    });
  } else {
    let data = await conferenceModel
      .find({ apply_status: 1 })
      .populate("apply_department")
      .lean();
    console.log(data, "数据");
    // 时间数据
    var Daysa = [];
    for (let i = 0; i < data.length; i++) {
      let start = new Date(data[i].use_start_time);
      let endstart = new Date(data[i].use_end_time);

      let startTimes = getConferenceList(start);
      console.log(startTimes, "新的开始时间");

      let endTimes = getConferenceList(endstart);
      console.log(endTimes, "新的结束时间");
      data[i].use_start_time = startTimes;
      data[i].use_end_time = endTimes;
      // 遍历时间
      let timeArray = [];
      let current = new Date(start);
      console.log(current, "current");
      // 过程
      while (current <= endstart) {
        timeArray.push(current);
        current = new Date(current.getTime() + 60 * 1000); // 增加一分钟
      }
      timeArray.forEach((time) => {
        let formattedTime = `${time.getFullYear()}/${time.getMonth() + 1
          }/${time.getDate()} ${time.getHours()}:${time.getMinutes()}`;
        console.log(formattedTime);
        let startDays = formattedTime.split(" ")[0].split("/")[2]; //开始号
        let startHours = formattedTime.split(" ")[1].split(":")[0]; //开始小时
        let startMints = formattedTime.split(":")[1]; //开始分钟

        //开始
        let addDays = {
          days: startDays,
          hours: startHours,
          minutes: startMints,
        };
        addDayToDaysa(addDays, Daysa);
      });
      console.log(Daysa, "数据时间结构"); // 输出添加后的完整数据结构
    }

    res.send({
      code: 200,
      message: "获取列表成功",
      data,
      Daysa,
    });
  }
  //
  function addDayToDaysa(dayObj, daysa) {
    // 遍历数组，检查是否已存在相同日期
    for (let i = 0; i < daysa.length; i++) {
      if (daysa[i].days === dayObj.days) {
        // 找到相同日期，继续遍历该日期下的小时
        for (let j = 0; j < daysa[i].hours.length; j++) {
          if (daysa[i].hours[j].hours === dayObj.hours) {
            // 找到相同小时，将新分钟添加到该小时下的数组中
            if (!daysa[i].hours[j].minutes.includes(dayObj.minutes)) {
              daysa[i].hours[j].minutes.push(dayObj.minutes);
            }
            return daysa;
          }
        }
        // 没有找到相同小时，创建新的小时对象，并将新分钟添加到该小时下的数组中
        let newHourObj = {
          hours: dayObj.hours,
          minutes: [dayObj.minutes],
        };
        daysa[i].hours.push(newHourObj);
        return daysa;
      }
    }
    // 没有找到相同日期，创建新的日期对象，并将新小时和新分钟添加到该日期下
    let newHourObj = {
      hours: dayObj.hours,
      minutes: [dayObj.minutes],
    };
    let newDayObj = {
      days: dayObj.days,
      hours: [newHourObj],
    };
    daysa.push(newDayObj);
    return daysa;
  }

  // 封装range(start,end)函数输出：[8, 9, 10, 11, 12]
  function range(start, end) {
    let result = [];
    for (let i = start; i <= end; i++) {
      result.push(i);
    }
    return result;
  }
  // 转换时间封装
  function getConferenceList(roriginalTimeeq) {
    let startTime =
      roriginalTimeeq.toLocaleString("en-US", {
        timeZone: "Asia/Shanghai",
      }) + "";
    let date = new Date(startTime);
    let year = date.getFullYear();
    let month = date.getMonth() + 1; // 月份是从 0 开始的，所以要加 1
    let day = date.getDate();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();

    // 将月、日、小时、分钟、秒转换为两位数的字符串形式
    month = String(month).padStart(2, "0");
    day = String(day).padStart(2, "0");
    hours = String(hours).padStart(2, "0");
    minutes = String(minutes).padStart(2, "0");
    seconds = String(seconds).padStart(2, "0");

    let formattedTime = `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
    console.log(formattedTime);
    return formattedTime;
  }
  //   封装时间差
  function getTimeDifference(startTime, endTime) {
    // 创建两个 Date 对象分别表示开始时间和结束时间
    let startDate = new Date(startTime);
    let endDate = new Date(endTime);

    // 计算时间间隔（单位：毫秒）
    let timeDifference = endDate - startDate;

    // 将时间间隔转换为天、小时、分钟和秒
    let days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
    let hours = Math.floor(
      (timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
    );
    let minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);
    let useDatas = { days, hours, minutes };
    console.log(days, hours, minutes, seconds, "使用时间差", useDatas);
    return useDatas;
  }
  // .populate("use_type")
  // .populate("apply_department")
  // .skip(skip)
  // .limit(limit);
});
// 会议添加
router.post("/create", (req, res) => {
  conferenceModel.create(req.body);
  res.send({
    code: 200,
    message: "创建成功",
    type: "success",
  });
});

// 会议模块    修改
router.post("/update", async (req, res) => {
  let { _id } = req.body;
  await conferenceModel.updateOne({ _id }, req.body);
  res.send({
    code: 200,
    message: "修改成功",
    type: "success",
  });
});

//  会议模块 删除接口
router.post("/delete", async (req, res) => {
  let { _id } = req.body;
  await conferenceModel.deleteOne({ _id });
  res.send({
    code: 200,
    message: "删除成功",
    type: "success",
  });
});

// 会议模块   会议详情
router.post("/details", async (req, res) => {
  let { _id } = req.body;
  let data = await conferenceModel
    .find({ _id })
    .populate("use_type")
    .populate("apply_department");
  res.send({
    code: 200,
    msg: "会议详情返回",
    type: "success",
    data,
  });
});

// 会议模块  部门添加
router.post("/deparmentCreate", async (req, res) => {
  deparmentModel.create(req.body);
  res.send({
    code: 200,
    msg: "会议部门添加成功",
    type: "success",
  });
});

// 会议模块   部门查询
router.get("/deparmentList", async (req, res) => {
  let data = await deparmentModel.find();
  res.send({
    code: 200,
    msg: "部门列表获取成功",
    type: "success",
    data,
  });
});

// 会议模块  类型查询   添加
router.post("/typeCreate", async (req, res) => {
  typeModel.create(req.body);
  res.send({
    code: 200,
    msg: "会议类型添加成功",
    type: "success",
  });
});

//  会议模块  类型查询
router.get("/typeList", async (req, res) => {
  let data = await typeModel.find();
  res.send({
    code: 200,
    msg: "类型列表获取成功",
    type: "success",
    data,
  });
});
//会议教室
router.get("/typeClass", async (req, res) => {
  let data = await typeClassModel.find();
  res.send({
    code: 200,
    msg: "会议教室列表获取成功",
    type: "success",
    data,
  });
});

// 批量导入
router.post("/importExcel", async (req, response) => {
  console.log('asdasdas')
  let form = new multiparty.Form();
  form.uploadDir = "assets";
  form.parse(req, (err, files, filed) => {
    let excelContent = xlsx.parse(filed.file[0].path);
    console.log(excelContent);
    let map = {
      会议主题: "conference_name",
      会议名称: "conference_theme",
      开始使用时间: "use_start_time",
      结束使用时间: "use_end_time",
      使用类型: "use_type",
      申请人: "apply_name",
      申请部门: "apply_department",
      申请时间: "apply_time",
      申请状态: "apply_status",
      检查状态: "check_status",
    };
    let typeList = excelContent[0].data[0]; // 第一行的标题
    console.log(typeList);
    let data = excelContent[0].data.slice(1); // 所对应的数据
    data.forEach((list) => {
      let json = {
        conference_name: "",
        conference_theme: "",
        use_start_time: "",
        use_end_time: "",
        use_type: "",
        apply_name: "",
        apply_department: "",
        apply_time: "",
        apply_status: "",
        check_status: "",
      };
      list.forEach((item, index) => {
        let key = map[typeList[index]];
        json[key] = item;
      });
      let {
        conference_name,
        conference_theme,
        use_start_time,
        use_end_time,
        use_type,
        apply_name,
        apply_department,
        apply_time,
        apply_status,
        check_status,
      } = json;
      conferenceModel
        .find({
          conference_name,
          conference_theme,
          use_start_time,
          use_end_time,
          use_type,
          apply_name,
          apply_department,
          apply_time,
          apply_status,
          check_status,
        })
        .then((res) => {
          if (res) {
            let j = { ...json };
            conferenceModel
              .updateOne(
                {
                  conference_name: j.conference_name,
                  conference_theme: j.conference_theme,
                  use_start_time: j.use_start_time,
                  use_end_time: j.use_end_time,
                  use_type: j.use_type,
                  apply_name: j.apply_name,
                  apply_department: j.apply_department,
                  apply_time: j.apply_time,
                  apply_status: j.apply_status,
                  check_status: j.check_status,
                },
                j
              )
              .then((res) => {
                console.log("update typeList");
              });
          } else {
            conferenceModel.create(json).then((res) => {
              console.log("create typeList");
            });
          }
        });
    });
    response.send({
      code: 200,
      message: "上传成功",
      type: "success",
    });
  });
});

// 教室数据导出 ，分页加异步
router.get("/exportExcel", async (req, res) => {
  /**
   * conference_name
   * conference_theme
   * use_type.type_name
   * apply_name
   * apply_department.deparment_name
   * apply_time
   * apply_status
   * check_status
   */
  let data = await conferenceModel.find().populate("use_type")
    .populate("apply_department")
  const workbook = new ExcelJS.stream.xlsx.WorkbookWriter();
  const sheet = workbook.addWorksheet('My Meeting'); // 添加工作表
  const moreConfig = {
    page: 0,
    limit: data.length >= 5000 ? 5000 : data.length,
  };
  sheet.addRow(['会议主题', '会议名称', '使用类型', '申请人', '申请部门', '申请时间', '申请状态', '检查状态']).commit()
  const totalPage = Math.ceil(data.length / moreConfig.limit); // 加入一百页
  const write = async () => {
    if (moreConfig.page >= totalPage) {
      console.log('交工作簿');
      await workbook.commit(); // 交工作簿，即写入

      return;
    }
    console.log('\n\当前处理 page ', moreConfig.page);
    for (let i = 0; i < moreConfig.limit; i++) {
      let idx = moreConfig.page * moreConfig.limit + i
      if (Number(idx) >= data.length) break
      sheet.addRow([
        data[idx].conference_name,
        data[idx].conference_theme,
        data[idx].use_type.type_name,
        data[idx].apply_name,
        data[idx].apply_department.deparment_name,
        data[idx].apply_time,
        data[idx].apply_status,
        data[idx].check_status,
      ]).commit(); // 添加行，commit（）是将添加的行提交
      idx = null
    }
    moreConfig.page += 1;
    // 使用 setTimeout 模拟查询数据库时间
    new Promise((res) => {
      setTimeout(() => {
        res(write());
      }, 0);
    });
  };
  // 告诉浏览器这是一个二进制文件
  res.setHeader(
    'Content-Type',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  );
  // 告诉浏览器这是一个需要下载的文件
  res.setHeader(
    'Content-Disposition',
    `attachment; filename=${encodeURIComponent('会议表')}.xlsx`
  );
  workbook.stream.pipe(res);
  Promise.resolve().then(write);
  res.send({
    code: 200
  })
});

module.exports = router;
